package com.itchen.school.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.util.Calendar;
import java.util.Date;

public class DateUtils extends SysDateUtils {

    /**
     * 将某日期的时间部分归零
     */
    public static Date zeroTimePart(Date d) {
        Calendar calendar = getCalendar();
        if (null != d) calendar.setTime(d);
        calendar.set(
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH), 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return new Date(calendar.getTimeInMillis());
    }

    /**
     * 按照生日获取年龄，参数生日时间戳
     */
    public static Integer calculateAge(Long birthdayTimestamp) {
        Long nowTimestamp = System.currentTimeMillis();
        long diffTimestamp = nowTimestamp - birthdayTimestamp;
        return Long.valueOf(diffTimestamp / 1000 / 60 / 60 / 24 / 365).intValue();
    }

    /**
     * 获取某一天开始时间
     */
    public static Date getStartOfDay(Date date) {
        Calendar cal=Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);//0点
        cal.set(Calendar.MINUTE, 0);//0分
        cal.set(Calendar.SECOND, 0);//0秒
        cal.set(Calendar.MILLISECOND, 0);
        return cal.getTime();
    }

    /**
     * 获取某一天结束时间
     */
    public static Date getEndOfDay(Date date) {
        Calendar cal=Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 23);//23点
        cal.set(Calendar.MINUTE, 59);//59分
        cal.set(Calendar.SECOND, 59);//59秒
        cal.set(Calendar.MILLISECOND, 999);
        return cal.getTime();
    }

    /**
     * HHmmdd格式转毫秒 HH:mm:ss HH:mm HH
     */
    public static Long HHmmss2Millisecond(String time) {
        if (StringUtils.isEmpty(time)) return 0L;
        String[] split = time.split(":");
        return Long.parseLong(split[0])*60*60*1000L
                + (split.length>=2 ? (Long.parseLong(split[1])*60*1000L) : 0)
                + (split.length>=3 ? (Long.parseLong(split[2])*1000L) : 0);
    }

}
